import { defineStore } from "pinia";
import { store } from "@/store";
import HMI_SETTING_AREA_API from "@/api/hmi/setting-area.api";
import { ref } from "vue";

/**
 * 定值区 Store
 */
export const useAreaSettingStore = defineStore("areaSetting", () => {
  // 当前定值区
  const currentArea = ref<number>(0);
  // 定值区列表
  const areaList = ref<number[]>([]);

  /**
   * 设置当前定值区
   * @param area 定值区编号
   */
  const setCurrentArea = (area: number) => {
    currentArea.value = area;
  };

  /**
   * 设置定值区列表
   * @param list 定值区编号数组
   */
  const setAreaList = (list: number[]) => {
    areaList.value = list;
  };

  /**
   * 获取定值区列表
   * @returns Promise<number[]> 定值区编号数组
   */
  const fetchSettingAreaList = async (): Promise<number[]> => {
    try {
      const res = await HMI_SETTING_AREA_API.fetchSettingAreaList();
      areaList.value = res;
      return res;
    } catch (error) {
      // TODO: 可以根据实际需求抛出错误或处理
      console.error("fetchSettingAreaList error:", error);
      throw error;
    }
  };

  return {
    currentArea,
    areaList,
    setCurrentArea,
    setAreaList,
    fetchSettingAreaList,
  };
});

/**
 * 适用于 setup 之外的场景
 */
export function useAreaSettingStoreHook() {
  return useAreaSettingStore(store);
}
